<template>
  <div
  v-loading="loading"
  id="market">
    <div style="margin-bottom: 20px; margin-top: 10px;">
      <!-- <el-button @click="onBuildHorse">Create horse</el-button> -->
    </div>

    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane label="For Sale" name="1"></el-tab-pane>
      <el-tab-pane label="All" name="2"></el-tab-pane>
    </el-tabs>
    <el-scrollbar class="scroll-view">
      <div class="scroll-content">
        <el-row>
            <el-col :span="8" v-for="(o, idx) in validHorses" :key="idx" class="card-col">
              <el-card :body-style="{ padding: '0px' }" class="card-cell h-center" @click.native="onHorseClicked(o.id)">
                <!-- <img src="~examples/assets/images/hamburger.png" class="image"> -->
                <div style="margin-top: 10px;margin-bottom: 10px;">
                  <div v-if="o.isSale">For sale = {{o.eth}} ETH</div>
                </div>

                <ve-radar
                  width="280px"
                  height="220px"
                  :data="o.chartData"
                  :settings="chartSettings"
                  :tooltip-visible="false"
                  :legend-visible="true"
                  :colors="colors"
                  :extend="extend"
                  class="skill-charts"></ve-radar>

                <el-rate
                  v-model="o.rateValue"
                  disabled
                  class="rate">
                </el-rate>

                <div class="card-bottom h-justify">
                  <img class="circle" :src="o.imgUrl" width="100px" height="100px">
                  <span class="v-bottom" style="color: #00ff00;">
                    <div>{{ o.name }}</div>
                  </span>
                  <span class="trailing-4 v-bottom">
                    <div >Gen{{o.generationNum}}</div>
                  </span>
                </div>
              </el-card>
              
            </el-col>
        </el-row>
      </div>
    </el-scrollbar>
</div>
</template>

<script>
  export default {
    name: 'market',
    data: function () {
      this.extend = {
        series: {
          label: {
            normal: {
              show: true
            }
          }
        }
      }

      this.chartSettings = {
        dimension: [],
        // 速度 加速度 力量 耐力 敏捷性 平衡性 弹跳 反应速度
        metrics: ['Speed', 'Acceleration', 'Strength', 'Endurance', 'Agile', 'Balancing', 'Bouncing', 'Reaction'],
        dataType: 'normal',
        min: [0, 0, 0, 0, 0, 0, 0, 0],
        max: [100, 100, 100, 100, 100, 100, 100, 100]
      }

      this.colors = [
        '#00000000',
        '#2f4554'
      ]

      return {
        loading: true,
        user: this.$store.state.user,
        currentDate: new Date(),
        activeName: '1',
        allHorsesIds: [],
        validHorses: []
      }
    },
    mounted () {
      console.log('Market form mounted')

      this.handleTabClick()
    },
    methods: {
      // 接口调用
      getSellingHorses () {
        this.$root.callMatch({
          isProtected: false,
          params: null,
          methodName: API.SELLING,
          methodType: 'GET',
          success: data => {
            console.log('selling = ' + JSON.stringify(data))
            this.allHorsesIds = data

            this.renderHorses()
          },
          failure: null
        })
      },
      // 事件处理
      handleTabClick () {
        console.log('tab click = ' + this.activeName)

        this.loading = true

        if (this.activeName === '1') {
          this.getSellingHorses()
        } else if (this.activeName === '2') {
          this.getAllHorses()
        }
      },
      onBuildHorse () {
        this.$root.callMatch({
          // isProtected: false,
          params: '124',
          methodName: API.CREATE_HORSE,
          methodType: 'POST',
          event: 'Birth',
          success: data => {
            console.log('horse create = ' + JSON.stringify(data))
            this.aAttributesOfHorse = data
          },
          failure: null
        })
      },
      onHorseClicked (value) {
        console.log('onHorseClicked')

        this.$router.push({
          path: '/horse',
          query: {
            id: value
          }
        })
      },
      // 接口
      getAllHorses () {
        this.$root.callMatch({
          params: null,
          methodName: API.TOTAL_SUPPLY,
          methodType: 'GET',
          success: data => {
            console.log('horse counts = ' + JSON.stringify(data))

            var worldHorseCounts = data

            this.allHorsesIds = []

            // 循环获取所有马
            for (var i = 1; i <= worldHorseCounts; i++) {
              this.allHorsesIds.push(i)
            }

            this.renderHorses()
          },
          failure: null
        })
      },
      // 渲染逻辑
      renderHorses () {
        this.validHorses = []

        var ids = this.allHorsesIds.filter(_ => parseInt(_) !== 0)

        // 获取马的详情
        ids.forEach(_ => {
          this.$root.callMatch({
            isProtected: false,
            params: _,
            methodName: API.GET_HORSE_WITH_AUCTION,
            methodType: 'GET',
            success: data => {
              console.log(JSON.stringify(data))

              // [ genes, birthTime, cooldownEndBlock, damId, sireId, siringWithId, cooldownIndex, generation, isIco ]
              var gen = data[0] // 基因
              var speedValue = parseInt(gen.slice(0, 2))
              var accelerationValue = parseInt(gen.slice(2, 4))
              var strengthValue = parseInt(gen.slice(4, 6))
              var enduranceValue = parseInt(gen.slice(6, 8))
              var agileValue = parseInt(gen.slice(8, 10))
              var balancingValue = parseInt(gen.slice(10, 12))
              var bouncingValue = parseInt(gen.slice(12, 14))
              var reactionValue = parseInt(gen.slice(14, 16))

              var generationNum = data[7]

              var horse = {}

              horse.isSale = data[9]
              horse.id = _
              horse.name = HORSE_NAMES[horse.id]
              horse.imgUrl = require(`../../assets/img/horses/${_}.jpg`)
              horse.chartData = {
                rows: [
                  { 'Speed': 100,
                    'Acceleration': 100,
                    'Strength': 100,
                    'Endurance': 100,
                    'Agile': 100,
                    'Balancing': 100,
                    'Bouncing': 100,
                    'Reaction': 100
                  },
                  {
                    'Speed': speedValue,
                    'Acceleration': accelerationValue,
                    'Strength': strengthValue,
                    'Endurance': enduranceValue,
                    'Agile': agileValue,
                    'Balancing': balancingValue,
                    'Bouncing': bouncingValue,
                    'Reaction': reactionValue
                  }
                ]
              }

              var rateValue = (speedValue + accelerationValue + strengthValue + enduranceValue + agileValue + balancingValue + bouncingValue + reactionValue) / 160
              horse.rateValue = Math.ceil(rateValue)

              horse.generationNum = parseInt(generationNum)

              horse.eth = 0

              this.validHorses.push(horse)

              // 将loading隐藏
              this.loading = false

              // 获取当前价格
              this.$root.callMatch({
                isProtected: false,
                // token_id
                params: _,
                methodName: API.GET_CURRENT_PRICE,
                methodType: 'GET',
                success: data => {
                  console.log('cancel = ' + JSON.stringify(data))

                  horse.eth = parseInt(data) / 1000000000000000000
                },
                failure: null
              })
            },
            failure: null
          })
        })
      }
    }
  }

  import { API, HORSE_NAMES } from '../../util/constants'
</script>

<style scoped>
#market {
  width: 100%;
  height: 100%;
  margin-top: 78px;
  margin-left: 12px;
}

.scroll-view {
  height: 100%;
}

.scroll-content {
  margin-top: 10px;
  margin-bottom: 10px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

/* 马区域的css */

.card-cell {
  height: 424px;
  max-width: 200;
}

.card-col {
  width: 24%;
  margin: 4px;
}

.card-bottom {
  margin-top: 8px;
}

.skill-charts {
  /* padding-top: 0; */
  /* margin-top: 0; */
  /* width: 100%; */
  /* margin-top: -20px; */
  /* height: 200px; */
  max-height: 290px;
  max-width: 380px;
  /* margin: 10px; */
}

.card-down {
  bottom: 0px;
}

.rate {
  margin-top: 10px;
}

</style>
